<?php

namespace app\common\service\shop\mercadolibre;

use think\facade\Cache;

/**
 * Mercadolibre
 * @package app\common\service\shop\mercadolibre
 * @Description 美客多跨境平台接口服务
 * @author xuli
 * @date 2024-10-18 09:04
 */
class BaseApi
{

    protected $shop_id = '';

    // 应用ID
    protected $appid = '';

    // 应用密钥
    protected $client_secret = '';

    // 缓存key
    protected $cache_token = 'mercadolibre_token_';
    protected $cache_refresh_token = 'mercadolibre_refresh_token_';

    // 账号token
    protected $access_token = '';

    protected $refresh_token = '';

    protected $redirect_uri = '';

    // 错误信息
    public $err_msg = '';

    /**
     * setConfig
     *
     * @Description 设置配置
     * @author wangqinghui
     * @date 2024-10-14 16:46
     */
    public function setConfig()
    {

    }

    protected function getCode()
    {
        // get
        $url = 'https://global-selling.mercadolibre.com/authorization?response_type=code&client_id=' . $this->appid . '&redirect_uri=' . $this->redirect_uri;
        $this->http_request('get', $url, [], []);
    }

    /**
     * @Description 获取token
     * @param $code
     * @return boolean
     */
    public function getToken($code)
    {
        // post
        $url = 'https://api.mercadolibre.com/oauth/token?grant_type=authorization_code&client_id=' . $this->appid . '&client_secret='. $this->client_secret .'&code=' . $code . '&redirect_uri=' . $this->redirect_uri;
        $header = ['Content-Type: application/json'];
        $return_data = $this->http_request('post', $url, $header, []);
        if($return_data) {
            $this->access_token = $return_data['access_token'];
            $this->refresh_token = $return_data['refresh_token'];
            // 缓存token
            Cache::set($this->cache_token . $this->shop_id, $this->access_token, 10000);
            // 缓存刷新token
            Cache::set($this->cache_refresh_token . $this->shop_id, $this->refresh_token, 10800);
            return true;
        } else {
            $this->err_msg = '获取token失败';
            return false;
        }
    }

    /**
     * 刷新token
     * @return boolean
     */
    protected function refreshToken()
    {
        // 获取refresh_token
        $refresh_token = Cache::get($this->cache_refresh_token . $this->shop_id);
        if(!empty($refresh_token)) {
            // 使用刷新token获取token
            $url = 'https://api.mercadolibre.com/oauth/token?grant_type=refresh_token&client_id=' . $this->appid . '&client_secret=' . $this->client_secret.'&refresh_token=' . $refresh_token;
            $header = ['Content-Type: application/json'];
            $return_data = $this->http_request('post', $url, $header, []);
            if($return_data) {
                $this->access_token = $return_data['access_token'];
                $this->refresh_token = $return_data['refresh_token'];
                // 缓存token
                Cache::set($this->cache_token . $this->shop_id, $this->access_token, 10000);
                // 缓存刷新token
                Cache::set($this->cache_refresh_token . $this->shop_id, $this->access_token, 10800);
                return true;
            } else {
                $this->err_msg = '刷新token失败';
                // 清空refresh_token
                Cache::delete($this->cache_token . $this->shop_id);
                Cache::delete($this->cache_refresh_token . $this->shop_id);
                return false;
            }
        } else {
            // 当刷新token也过期后，重新请求code和token
            $this->getCode();
        }
    }

    protected function shopApi($type, $shop_id, array $data = [])
    {
        $url = '';
        $body = [];
        $header = ["Content-Type: application/json"];
        $this->shop_id = $shop_id;
        $http_type = '';

        // 获取token
        $this->getAllToken();

        switch ($type) {
            case 'add_items': // 添加产品
                $url = "https://api.mercadolibre.com/items";
                $header[] = "Authorization: Bearer {$this->access_token}";
                $http_type = 'POST';
                $body = $data;
                break;
            case 'add_description': // 添加描述
                $url = "https://api.mercadolibre.com/marketplace/items/{$data['item_id']}/description";
                $header[] = "Authorization: Bearer {$this->access_token}";
                $body = $data['body'];
                $this->http_request('post', $url, $header, $body);
                break;
            case 'site_list': // 获取用户站点列表
                $url = "https://api.mercadolibre.com/marketplace/users/{$data['user_id']}";
                $header[] = "Authorization: Bearer {$this->access_token}";
                $http_type = 'GET';
                break;
            case 'change_stock': // 改变库存
                $body = $data['body'];
                $url = "https://api.mercadolibre.com/global/items/{$data['item_id']}";
                $header[] = "Authorization: Bearer {$this->access_token}";
                break;
            case 'search_goods': // 搜索商品
                $url = "https://api.mercadolibre.com/items?ids={$data['item_ids']}";
                $header[] = "Authorization: Bearer {$this->access_token}";
                $http_type = 'GET';
                break;
            case 'search_orders': // 获取订单列表
                $url = "https://api.mercadolibre.com/marketplace/orders/search?" . $data['filter'];
                $header[] = "Authorization: Bearer {$this->access_token}";
                $http_type = 'GET';
                break;
            case 'order_detail': // 订单详情
                $url = "https://api.mercadolibre.com/marketplace/orders/{$data['order_id']}";
                $header[] = "Authorization: Bearer {$this->access_token}";
                $http_type = 'GET';
                break;

        }

        $result = $this->http_request($http_type, $url, $header, $body);
        return json_decode($result, true);
    }

    protected function getAllToken()
    {
        // 通过店铺ID获取到相关的appid配置或者
        $token = Cache::get($this->cache_token . $this->shop_id);
        if(!empty($token)) {
            $this->access_token = $token;
            return true;
        }
        // 当access_token不存在时重新请求token
        $this->refreshToken();
    }



    /**
     * 发送请求
     * @param $type
     * @param $url
     * @param array $header
     * @param array $data
     * @return mixed
     */
    private function http_request($type, $url, array $header, array $data){
        $curl = curl_init();
        // curl参数配置-----------------------------------------
        $curl_params = [];
        //自定义header
        if(!empty($header)){
            $curl_params[CURLOPT_HTTPHEADER] = $header;
        }
        $curl_params[CURLOPT_URL] = $url; //请求url地址
        // $curl_params[CURLOPT_HEADER] = false; //是否返回响应头信息
        $curl_params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $curl_params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $curl_params[CURLOPT_MAXREDIRS] =  10; //指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的。
        $curl_params[CURLOPT_ENCODING] = ''; //支持的编码有"identity"，"deflate"和"gzip"。如果为空字符串""，请求头会发送所有支持的编码类型
        //$curl_params[CURLOPT_TIMEOUT] = 15; //设置cURL允许执行的最长秒数
        // $curl_params[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; //版本
        if(!empty($type)) {
            $curl_params[CURLOPT_CUSTOMREQUEST] = $type;
        }

        //如果有数据 则设置为post传输
        if (!empty($data)){
            $curl_params[CURLOPT_CUSTOMREQUEST] = 'POST';
            $curl_params[CURLOPT_POSTFIELDS] =  $data;
        }
        //下两行禁用证书
        $curl_params[CURLOPT_SSL_VERIFYPEER] = false;
        $curl_params[CURLOPT_SSL_VERIFYHOST] = false;
        // curl参数配置-----------------------------------------

        curl_setopt_array($curl, $curl_params);

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }


}
